package com.tenton.servlet;

import com.tenton.pojo.Book;
import com.tenton.service.BookService;
import com.tenton.service.Impl.BookServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;

/**
 * @Date: 2021/1/19
 * @Author: Tenton
 * @Description: 根据用户Id删除用户
 */
@WebServlet(name = "AddBookServlet",urlPatterns = "/addBookServlet")
public class AddBookServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码格式，防止乱码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        BookService bookService = new BookServiceImpl();
        //图书Id
        String bookId = request.getParameter("id");
        int id = 0;
        //判断是否为空，然后再进行转化为int类型
        if(bookId !=null && !bookId.equals("")){
            id = Integer.parseInt(bookId);
        }
        //图书名称
        String bookName = request.getParameter("bookName");
        //作者
        String author = request.getParameter("author");
        //出版社
        String press = request.getParameter("press");
        //图书单价
        String bookPrice = request.getParameter("price");
        BigDecimal price = new BigDecimal(bookPrice);
        //数量
        int num = Integer.parseInt(request.getParameter("num"));
        //图书插图 路径
        String image = request.getParameter("image");
        if (id > 0) {
            //创建一个Book实体，保存前端传递过来的值
            Book book = new Book(id, bookName, author, press, price, num, image);
            int result = bookService.insertBook(book);
            //判断是否添加成功
            if (result > 0) {
                response.getWriter().print("<script>alert('添加成功!')</script>");
                response.sendRedirect("/listBookServlet");
            } else {
                response.getWriter().write("添加失败，2秒后自动跳转到主界面");
                response.setHeader("Refresh", "3;URL=/listBookServlet");
            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
